package com.gxpt.app.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.R;
import com.gxpt.app.adapter.getgoodslist_Adapter;
import com.gxpt.app.bean.getgoodslist_bean;
import com.gxpt.app.bean.hotgoods_bean;
import com.utils.ScreenUtils;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.utils.picasso.PicassoUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_mall_goods_list)
public class Activity_mall_goods_list extends BaseActivity {

    /**服务器端一共多少条数据*/
    private static final int TOTAL_COUNTER = 10000;//如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断

    /**每一页展示多少条数据*/
    private static final int REQUEST_COUNT = 20;

    /**已经获取到多少条数据了*/
    private static int mCurrentCounter = 0;

    private getgoodslist_Adapter mDataAdapter = null;

    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;

    ///////////////////
    int page_num  = 1;
    int page_size = 20;


    @ViewInject(R.id.mLRecyclerView)
    LRecyclerView mLRecyclerView;

    private View topView;

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.type_layout)
    LinearLayout type_layout;

    LinearLayout TJ_layout;

    int pic_view_width = 0;
    int pic_view_hight = 0;

    int index_sub=0;
    String type_main_id = "";
    String type_sub_id  = "";


    String[] titles;
    String[] ids;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle a = getIntent().getBundleExtra("DATA");
        if(a != null ){
            titles = a.getStringArray("data1");
            ids    = a.getStringArray("data2");

            int index = a.getInt("TYPES_MAIN_INDEX");
            index_sub = a.getInt("TYPES_SUB_INDEX");

            type_main_id  = a.getString("TYPES_MAIN_ID");
            type_sub_id   = a.getString("TYPES_SUB_ID");
        }
        x.view().inject(this);
        initView();
        initData();
    }

    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_service_all_types));
        int Sviewwidth  = ScreenUtils.getScreenWidth(context);//
        pic_view_width  = Sviewwidth-AppUtils.dip2px(context,10*2);
        pic_view_hight  = pic_view_width/16*9;

        initTopView();
        ///////////////////////////////////////////
        mDataAdapter = new getgoodslist_Adapter(context);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mLRecyclerView.setAdapter(mLRecyclerViewAdapter);

//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.split)
//                .build();

        mLRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        mLRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mLRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mLRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //add a HeaderView
        mLRecyclerViewAdapter.addHeaderView(topView);

        mLRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDataAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
                mCurrentCounter = 0;
                do_Refresh();
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能

        mLRecyclerView.setLoadMoreEnabled(true);

        mLRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                do_LoadMore();
            }
        });

        //设置头部加载颜色
        mLRecyclerView.setHeaderViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载颜色
        mLRecyclerView.setFooterViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载文字提示
        mLRecyclerView.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        mLRecyclerView.refresh();

        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {
                    getgoodslist_bean.getgoodslist item = mDataAdapter.getDataList().get(position);

                    Bundle b = new Bundle();
                    b.putString("ID",item.id);
                    jumpActivity(Activity_webview.class,b,false);



                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
//                ItemModel item = mDataAdapter.getDataList().get(position);
//                T.show(getApplicationContext(), "onItemLongClick - " + item.title,1);
            }
        });
    }

    private void do_Refresh(){
        page_num = 1;
        toNet_getgoodslist();//最新
    }

    private void do_LoadMore(){
        page_num += 1;
        toNet_getgoodslist();//最新
    }
    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(ArrayList<getgoodslist_bean.getgoodslist> list) {

        mDataAdapter.addAll(list);
        mCurrentCounter += list.size();
    }

    private void initTopView(){
        topView = LayoutInflater.from(context).inflate(R.layout.common_mall_goods_list_recommend,null, false);
        topView.setLayoutParams(new LRecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
        TJ_layout = (LinearLayout)topView.findViewById(R.id.TJ_layout);
    }


    @Override
    public void initData() {
        init_List_type();
    }

    @Event(value={R.id.toback})
    private void getEvent(View view){
        switch(view.getId()){

            case R.id.toback:
                closeActivity();
                break;
        }
    }

    private void init_List_type(){

        if(titles == null)   return;
        if(titles.length<=0) return;

        type_layout.removeAllViews();

        for (int a = 0; a < titles.length; a++) {
            type_layout.addView(creatListTypeView(a));
        }
    }

    private View creatListTypeView(int id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_mall_types, null);

        TextView list_title = (TextView)convertView.findViewById(R.id.list_title);
        list_title.setText(titles[id]);

        TextView list_id = (TextView)convertView.findViewById(R.id.list_id);
        list_id.setText(ids[id]);

        LinearLayout line = (LinearLayout)convertView.findViewById(R.id.line);

        convertView.setId(id);

        if(index_sub == id){
            list_title.setTextColor(getResources().getColor(R.color.red));
            line.setBackgroundColor(getResources().getColor(R.color.red));
        }
        convertView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                int ViewID = v.getId();
                for(int a=0;a<type_layout.getChildCount();a++){
                    if(type_layout.getChildAt(a).getId() != ViewID){
                        TextView title = (TextView)type_layout.getChildAt(a).findViewById(R.id.list_title);
                        title.setTextColor(getResources().getColor(R.color.font_686868));

                        LinearLayout aa = (LinearLayout)type_layout.getChildAt(a).findViewById(R.id.line);
                        aa.setBackgroundColor(getResources().getColor(R.color.white));

                    }else{
                        TextView title = (TextView)type_layout.getChildAt(a).findViewById(R.id.list_title);
                        title.setTextColor(getResources().getColor(R.color.red));

                        LinearLayout aa = (LinearLayout)type_layout.getChildAt(a).findViewById(R.id.line);
                        aa.setBackgroundColor(getResources().getColor(R.color.red));

                    }
                }
//
////                main_id   = ""+ViewID;
////                main_name = ""+list_title.getText().toString();
//                type_sub.removeAllViews();
//                type_sub.removeAllViewsInLayout();
//                init_List_sub_type(ViewID);
            }
        });
        return convertView;
    }

    private void init_TJ_goods(List<getgoodslist_bean.getgoodslist> netDatas){
        if(netDatas == null)   return;
        if(netDatas.size()<=0) return;

        TJ_layout.removeAllViews();

        for (int a = 0; a < netDatas.size(); a++) {
            TJ_layout.addView(creat_TJ_goods_View(netDatas.get(a),a));
        }
    }

    private View creat_TJ_goods_View(getgoodslist_bean.getgoodslist netData,int id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_mall_index_list2, null);

        TextView list_title = (TextView)convertView.findViewById(R.id.list_title);
        list_title.setText(netData.goods_name);

        TextView txt_hidden_ID = (TextView)convertView.findViewById(R.id.txt_hidden_ID);
        txt_hidden_ID.setText(netData.id);

        TextView txt_price = (TextView)convertView.findViewById(R.id.txt_price);
        txt_price.setText(netData.sell_price);

        TextView txt_count = (TextView)convertView.findViewById(R.id.txt_count);
        txt_count.setText(netData.buy_num);

        txt_price.append(context.getString(R.string.txt_yuan));

        ImageView img_1= (ImageView)convertView.findViewById(R.id.img_1);
        if(netData.thumb.isEmpty()){
            PicassoUtils.Picasso_displayImage(context,R.mipmap.ic_launcher,pic_view_width,pic_view_hight,img_1);
        }else{
            PicassoUtils.Picasso_displayImage(context,netData.thumb,pic_view_width,pic_view_hight,img_1);
        }

        convertView.setId(id);
        convertView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                int ViewID = v.getId();
////                main_id   = ""+ViewID;
////                main_name = ""+list_title.getText().toString();
//                type_sub.removeAllViews();
//                type_sub.removeAllViewsInLayout();
//                init_List_sub_type(ViewID);
            }
        });
        return convertView;
    }




    //////NET DO
    private void toNet_recommendgoods(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shop");
            jsonBody.put("serviceName",          "Recommendgoods");

            jsonBody.put("one_id",               type_main_id);
            jsonBody.put("two_id",               type_sub_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i("toNet_hotgoods = "+jsonBody.toString());
        HttpUtils.http_post_string(Constant.URL_recommendgoods,jsonBody.toString(),do_recommendgoods);
    }

    StringCallback do_recommendgoods = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e("do_hotgoods = "+s);
            try{
                getgoodslist_bean data = new Gson().fromJson(s, getgoodslist_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        if(data.data.size()>0){
                            init_TJ_goods(data.data);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    private void toNet_getgoodslist(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shop");
            jsonBody.put("serviceName",          "getgoodslist");

            jsonBody.put("one_id",               type_main_id);
            jsonBody.put("two_id",               type_sub_id);
            jsonBody.put("page_size",            page_size);
            jsonBody.put("page_num",             page_num);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i("do_getgoodslist = "+jsonBody.toString());
        HttpUtils.http_post_string(Constant.URL_getgoodslist,jsonBody.toString(),do_getgoodslist);
    }

    StringCallback do_getgoodslist = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e("do_getgoodslist = "+s);
            try{
                getgoodslist_bean data = new Gson().fromJson(s, getgoodslist_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        if(data.data.size()>0){
                            addItems((ArrayList)data.data);
                            notifyDataSetChanged();
                        }else{
                            page_num -= 1;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
}
